package com.acme.bankapp.service.bank;

import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import com.acme.bankapp.domain.bank.client.Client;
import com.acme.bankapp.domain.bank.client.ClientRegistrationListener;
import com.acme.bankapp.service.bank.exception.ClientExistsException;

@SuppressWarnings("serial")
public class Bank implements java.io.Serializable {

	public static class PrintClientListener implements ClientRegistrationListener {
		@Override
		public void onClientAdded(Client c) {
			System.out.println(c);
		}
	}

	public int getCountClients() {
		return clients.size();
	}

	public void addClient(Client client) throws ArrayIndexOutOfBoundsException, ClientExistsException {
		if (getCountClients() == MAX_CLIENTS)
			throw new ArrayIndexOutOfBoundsException("The bank has already contains the maximum number of clients");
		if (!clients.add(client)) {
			throw new ClientExistsException();
		}
		for (ClientRegistrationListener listener : listeners) {
			listener.onClientAdded(client);
		}
	}

	public int getCountListeners() {
		return listeners.size();
	}

	public void addListener(ClientRegistrationListener listener) throws ArrayIndexOutOfBoundsException {
		if (getCountListeners() == MAX_LISTENER) {
			throw new ArrayIndexOutOfBoundsException("The bank has alreade contains the maximum number of clients");
		}
		listeners.add(listener);
	}

	public static final int MAX_LISTENER = 3;

	private List<ClientRegistrationListener> listeners;

	public static final int MAX_CLIENTS = 10;

	private Set<Client> clients;

	public Bank(ClientRegistrationListener[] listeners) throws ArrayIndexOutOfBoundsException {
		clients = new HashSet<Client>();
		this.listeners = new LinkedList<ClientRegistrationListener>();

		class DebugListener implements ClientRegistrationListener {
			@Override
			public void onClientAdded(Client c) {
				System.out.println("Client: " + c + "; time: " + new Date());
			}
		}
		addListener(new DebugListener());
		for (int i = 0 ; i < listeners.length; i++) {
			addListener(listeners[i]);
		}
	}

	public Set<Client> getClients() {
		return Collections.unmodifiableSet(clients);
	}
}